<template>
  <div class="add-dept ">
    <el-dialog
      :close-on-click-modal="false"
      title="新增部门"
      :visible="addshow"
      @close="cancel"
    >
      <el-form :model="form" ref="myform" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" placeholder="请选择">
            <el-option
              v-for="(item, index) in list"
              :key="index"
              :label="item.username"
              :value="item.username"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartmentApi,
  addDepartmentApi,
  getDepartmentByIdApi,
  editDepartmentByIdApi
} from '@/api/departments'
import { getEmployeesListApi } from '@/api/Employees.js'
export default {
  props: ['addshow', 'currentObj'],
  data () {
    return {
      form: {
        code: '',
        name: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称长度在1~50之间',
            trigger: 'blur'
          },
          {
            validator: async (rule, value, callback) => {
              const res = await getDepartmentApi()
              if (!this.form.id) {
                // 新增的规则 currentObj:要添加的子部门的上一级的节点
                res.data.depts.some(
                  item => item.name === value && item.pid === this.currentObj.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              } else {
                // 编辑的规则 currentObj：当前操作的部门对象
                // 与同级子部门名称不能重复，将自己从子部门排除掉
                res.data.depts.some(
                  item =>
                    item.name === value &&
                    item.pid === this.currentObj.pid &&
                    item.id !== this.form.id
                )
                  ? callback(new Error('部门名称不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '编码长度在1~50之间', trigger: 'blur' },
          {
            validator: async (rule, value, callback) => {
              // 获取所有的部门数据
              const res = await getDepartmentApi()
              if (!this.form.id) {
                // 新增
                // 判断所有的数据中的 code 是否与 value 相同
                res.data.depts.some(item => item.code === value)
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              } else {
                // 编辑
                // 判断所有的数据中的 code 是否与 value 相同
                res.data.depts.some(
                  item => item.code === value && item.id !== this.form.id
                )
                  ? callback(new Error('部门编码不能重复'))
                  : callback()
              }
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '介绍内容在1~300之间', trigger: 'blur' }
        ]
      },
      list: []
    }
  },
  methods: {
    async getEmployeesList () {
      const res = await getEmployeesListApi()
      //   console.log(res)
      this.list = res.data
    },
    async getItem (id) {
      const res = await getDepartmentByIdApi(id)
      console.log(res)
      this.form = res.data
    },
    cancel () {
      this.$emit('update:addshow', false)
      this.form = {
        code: '',
        name: '',
        manager: '',
        introduce: ''
      }
      this.$refs.myform.resetFields()
    },
    submit () {
      this.$refs.myform.validate(async val => {
        if (val) {
          if (!this.form.id) {
            await addDepartmentApi({
              ...this.form,
              pid: this.currentObj.pid === '-1' ? '' : this.currentObj.id
            })
          } else {
            await editDepartmentByIdApi(this.form)
          }
          this.$emit('update:addshow', false)
          this.$message.success('新增成功')
          this.$emit('updateList')
          this.form = {
            code: '',
            name: '',
            manager: '',
            introduce: ''
          }
        }
      })
    }
  },

  created () {
    this.getEmployeesList()
  }
}
</script>

<style lang="scss" scped>
.add-dept {
  border-radius: 8px;
  .el-dialog {
    .el-dialog__header {
      background-color: #529ecf;
    }
    .el-dialog__footer {
      .el-button--primary {
        background-color: #529ecf;
        border: 1px solid transparent;
        border-radius: 8px;
      }
    }
  }
}
</style>
